package com.mid;

/**
 * Created by Lxk on 2019/6/7.
 */
public class Solution445 {


    private ListNode reverseList(ListNode head){
        if(head==null){
            return null;
        }
        ListNode pre = null;
        ListNode next = null;
        while(head!=null){
            next = head.next;
            head.next = pre;
            pre = head;
            head = next;
        }
        return pre;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null){
            return l2;
        }
        if(l2==null){
            return l1;
        }
        ListNode cur1 = reverseList(l1),cur2 = reverseList(l2);
        boolean isAddFlag = false;
        ListNode head = new ListNode(0);
        ListNode cur = head;
        while(cur1!=null&&cur2!=null){
            int addNum = isAddFlag ? 1 : 0;
            if(cur1.val+cur2.val+addNum>=10){
                isAddFlag = true;
            }else{
                isAddFlag = false;
            }
            int num = (cur1.val+cur2.val+addNum)%10;
            ListNode node = new ListNode(num);
            cur.next = node;
            cur = cur.next;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        if(cur1==null){
            while(cur2 != null){
                int addNum = isAddFlag ? 1 : 0;
                if(addNum+cur2.val>=10){
                    isAddFlag = true;
                }else{
                    isAddFlag = false;
                }
                cur2.val = (cur2.val + addNum) % 10;
                cur.next = cur2;
                cur = cur.next;
                cur2 = cur2.next;
            }
        }
        if(cur2==null){
            while(cur1 != null){
                int addNum = isAddFlag ? 1 : 0;
                if(addNum+cur1.val>=10){
                    isAddFlag = true;
                }else{
                    isAddFlag = false;
                }
                cur1.val = (cur1.val + addNum) % 10;
                cur.next = cur1;
                cur = cur.next;
                cur1 = cur1.next;
            }
        }
        if(isAddFlag){
            ListNode node = new ListNode(1);
            cur.next = node;
        }
        return reverseList(head.next);
    }

    public static void main(String[] args) {
        ListNode node = new ListNode(8);
        ListNode node2 = new ListNode(9);
        ListNode node3 = new ListNode(9);
        node.next = node2;
        node2.next = node3;
        Solution445 solution445 = new Solution445();
        solution445.addTwoNumbers(node,new ListNode(2));
    }

}
